﻿using OF.Utility.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;

namespace CGT.GOP.Common
{
    public class FormsPrincipal
    {
        public const string LOGIN_NAME = "CGT_USR_INFO";

        /// <summary>
        /// 执行用户登录操作
        /// </summary>
        /// <param name="loginName">登录名</param>
        /// <param name="userData">与登录名相关的用户信息</param>
        /// <param name="expiration">登录Cookie的过期时间，单位：天。</param>
        public static void SignIn(UserInfo userData, int expiration)
        {
            if (userData == null)
                throw new ArgumentNullException("userData");

            // 1. 把需要保存的用户数据转成一个字符串。
            string data = null;
            if (userData != null)
                data = userData.ToString();


            // 2. 创建一个FormsAuthenticationTicket，它包含登录名以及额外的用户数据。
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                1, LOGIN_NAME, DateTime.Now, DateTime.Now.AddDays(1), false, data, "/");



            // 3. 加密Ticket，变成一个加密的字符串。
            string cookieValue = FormsAuthentication.Encrypt(ticket);


            // 4. 根据加密结果创建登录Cookie
            HttpCookie cookie = new HttpCookie(LOGIN_NAME, cookieValue);
            cookie.HttpOnly = true;
            cookie.Secure = FormsAuthentication.RequireSSL;
            cookie.Domain = FormsAuthentication.CookieDomain;
            cookie.Path = FormsAuthentication.FormsCookiePath;
            cookie.HttpOnly = true;//可以防止浏览器攻击窃取、伪造Cookie，但是客户端js无法读取到这个Cookie
            if (expiration > 0)
                cookie.Expires = DateTime.Now.AddDays(expiration);

            HttpContext context = HttpContext.Current;
            if (context == null)
                throw new InvalidOperationException();

            // 5. 写登录Cookie
            context.Response.Cookies.Remove(cookie.Name);
            context.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// 判断用户是否登陆，返回用户信息
        /// </summary>
        /// <returns></returns>
        public static UserInfo IsAuthenticated()
        {
            UserInfo usr = new UserInfo();

            var cookies = HttpContext.Current.Request.Cookies;
            if (cookies[LOGIN_NAME] != null && !string.IsNullOrEmpty(cookies[LOGIN_NAME].Value))
            {
                var tickets = FormsAuthentication.Decrypt(cookies[LOGIN_NAME].Value);
                try
                {
                    if (!string.IsNullOrEmpty(tickets.UserData))
                    {
                        usr.Parse(tickets.UserData);
                    }
                }
                catch (Exception ex)
                {
                    Log4netLog.Debug(ex.Message);
                }
            }
            return usr;
        }

        /// <summary>
        /// 退出
        /// </summary>
        public static void SignOut()
        {
            FormsAuthentication.SignOut();
        }
    }
}